<template>
	<div class="boxes-detail-AIConfiguration">
		<div class="config-manage-from-left">
			<div class="AIname">AI服务列表</div>
			<vue-scroll @handle-scroll="handleScroll">
				<ul class="main-left-list">
					<li
						:key="item.id"
						v-for="(item, index) in serviceList"
						class="main-left-list-item"
						:class="[activeIndex === index && 'active']"
						@click="onClickItem(item, index)"
					>
						<div class="AI-left">
							<div>
								<p>{{ item.aiSrvName }}</p>
							</div>
							<div>
								<a-switch
									:checked="item.aiSrvStatus === 1 ? true : false"
									size="small"
									@change="changeChecked(item, item.aiSrvStatus)"
								></a-switch>
							</div>
						</div>
					</li>
				</ul>
			</vue-scroll>
		</div>

		<main class="ai-service-page-main">
			<template v-if="serviceList?.length && hasAlgoAuth">
				<div class="general-bar">
					<div>
						<global-svg-icon icon-name="config-title-tri" style="vertical-align: sub" width="3px" height="18px"></global-svg-icon>
						<h6 class="text">存储信息</h6>
					</div>
					<div>
						<a-button v-auth="'ai-service-edit'" type="text" class="reset-button" :loading="resetLoading" @click="onReset"
							>恢复默认设置</a-button
						>
						<a-button v-auth="'ai-service-edit'" type="primary" :loading="formLoading" @click="onSubmit">保存</a-button>
					</div>
				</div>
				<vue-scroll @handle-scroll="handleScroll">
					<div class="form-wrap">
						<boxes-a-i-temp-form ref="serviceFormRef" v-if="serviceItem.aiSrvType === 100" :b-ai-server-id="mainId"></boxes-a-i-temp-form>

						<boxes-a-i-form ref="serviceFormRef" v-if="serviceItem.aiSrvType !== 100" :b-ai-server-id="mainId"></boxes-a-i-form>
					</div>
				</vue-scroll>
			</template>

			<no-algo-auth v-if="!hasAlgoAuth" :text="'当前设备未进行算法授权，请授权后使用本功能'"></no-algo-auth>
		</main>
	</div>
</template>

<script setup lang="ts">
import { WarningFilled } from '@ant-design/icons-vue';
import { Modal } from 'ant-design-vue';
import { g6DeepClone } from 'glasssix-utils-ts';
import { useDeleteModal } from '@/global-hooks/base.hooks';
import { obj2str } from '@/global-utils/base.utils';
import { BoxManageApi } from '../../../api';
import { BoxesAIForm, NoAlgoAuth, BoxesAITempForm } from '../../index';
import { beforeRouteLeaveWhiteList } from '../../../config';

defineOptions({ name: 'BoxAiConf' });

const { setOpenDeleteModal } = useDeleteModal();

const $message: any = inject('$message');
let cacheData: any = null;

const hasAlgoAuth = ref<boolean>(true); // 是否算法授权

// 离开提示
const leaveInfo = '信息未保存，确认离开？';
const route = useRoute();

// 盒子序列号
const boxSerial = ref<string>('');
// 盒子名称
const name = ref<string>('');

// 算法id 后端主键id
const mainId = ref<number>();

// 当前选中项
const activeIndex = ref<number>(0);

const formLoading = ref<boolean>(false);
const serviceFormRef = ref<InstanceType<typeof BoxesAIForm>>();

// 默认设置loading
const resetLoading = ref<boolean>(false);
// 恢复默认设置
const onReset = async (): Promise<void> => {
	resetLoading.value = true;
	const param = {
		boxSerial: boxSerial.value,
		id: mainId.value
	};
	const res: TsRes = await BoxManageApi.restoreAiSrvDefaultConfig(param);
	if (res.code === 0) {
		await getAiSrvList();
		resetLoading.value = false;
	}
};

// 保存通用规则配置
const onSubmit = async (): Promise<void> => {
	try {
		formLoading.value = true;
		const param = await serviceFormRef.value?.getFormData();
		const res: TsRes = await BoxManageApi.updateAiSrvConfig(param);
		if (res.code === 0) {
			cacheData = { ...param };
			$message.success('操作成功');
		}
		formLoading.value = false;
	} catch (error) {
		formLoading.value = false;
		console.log(error);
	}
};

const styleValue = reactive({
	'--header-height': '76px',
	'--main-height': '0px',
	'--border-bottom': '1px solid transparent'
});
const handleScroll = (vertical: Record<string, any>): void => {
	styleValue['--border-bottom'] = vertical.scrollTop > 5 ? '1px solid rgba(211, 211, 211, 0.2)' : '1px solid transparent';
};

/**
 * 服务列表点击
 */
const serviceItem = ref<any>({});
const onClickItem = async (item: any, index: number): Promise<void> => {
	const run = async (): Promise<void> => {
		mainId.value = item.id;
		activeIndex.value = index;
		cacheData = g6DeepClone(item);
		serviceItem.value = item;
		nextTick(() => {
			serviceFormRef.value?.setFormData(item);
		});
	};
	if (mainId.value !== item.id && dataCompare(run)) {
		run();
	}
};
// 服务列表
const serviceList = ref<any[]>([]);
// 获取AI服务列表数据
const getAiSrvList = async (): Promise<void> => {
	const res: TsRes = await BoxManageApi.queryAiSrvList(boxSerial.value);
	if (res.code === -17) {
		hasAlgoAuth.value = false;
		return;
	}
	if (res.code !== 0) {
		$message.error(res.message);
		return;
	}
	serviceList.value = res?.data || [];
	console.log(serviceList.value.length);
	cacheData = g6DeepClone(res?.data[activeIndex.value]);
	await nextTick();
	serviceFormRef.value?.setFormData(res?.data[activeIndex.value]);
	serviceList.value.length && onClickItem(res?.data[activeIndex.value], activeIndex.value);
};

/**
 * 数据比较
 * @callback 弹窗ok 执行函数
 * @return  true 数据一致 false 不一致
 */
const dataCompare = (callback: Function) => {
	const formData = serviceFormRef.value?.getFormDataSync();
	if (obj2str(cacheData) === obj2str(formData)) {
		return true;
	}

	Modal.confirm({
		class: 'global-delete-modal',
		width: 416,
		icon: h(WarningFilled),
		title: leaveInfo,
		okText: '确定',
		cancelText: '取消',
		content: '',
		onCancel: () => Modal.destroyAll(),
		onOk: () => callback()
	});
	return false;
};

// 修改AI服务列表状态
const changeChecked = async (item: any, checked: boolean | string | number): Promise<void> => {
	const param = {
		boxSerial: boxSerial.value,
		aiSrvStatus: checked === 0 ? 1 : 0,
		id: item.id
	};
	let name = checked === 0 ? '启用' : '禁用';
	const restartFun = async (): Promise<void> => {
		let res: TsRes = await BoxManageApi.updateAiSrvStatus(param);
		if (res.code === 0) {
			item.aiSrvStatus = checked === true ? 0 : 1;

			$message.success(`${name}成功`);
			getAiSrvList();
		}
	};
	const restartModalInfo = {
		title: `确定${name}`,
		okText: '确认',
		cancelText: '取消'
	};

	setOpenDeleteModal(restartFun, restartModalInfo);
};

onMounted(() => {
	boxSerial.value = route.query?.boxSerial as string;
	name.value = route.query?.name as string;

	getAiSrvList();
});

/**
 * ----------------------------------------------- 路由后置守卫 ---------------------------------------------
 */
onBeforeRouteLeave(async (to, _from, next) => {
	if (!hasAlgoAuth.value) {
		next();
		return;
	}
	if (!beforeRouteLeaveWhiteList.includes(to.path)) {
		dataCompare(next) && next();
	} else {
		next();
	}
});
</script>

<style lang="less">
.boxes-detail-AIConfiguration {
	display: flex;
	overflow: hidden;
	width: 100%;
	height: 100%;
	border-top: 1px solid @borderColor02;
	user-select: none;

	.config-manage-from-left {
		display: flex;
		width: 272px;
		height: calc(100vh - 220px);
		padding: 8px 16px;
		padding-right: 0;
		background-color: @background02;
		flex-direction: column;

		.AIname {
			margin-bottom: 22px;
			font-size: 14px;
			font-weight: 700;
			line-height: 22px;
			text-align: left;
			color: @text02;
		}

		.main-left-list {
			display: flex;
			overflow: auto;
			overflow: hidden;
			// overflow-y: scroll;
			flex: 1;
			flex-direction: column;
			gap: 8px 0;

			.main-left-list-item {
				height: 64px;
				margin-right: 16px;
				border-radius: 8px;
				padding: 0 16px;
				font-size: 16px;
				// justify-content: space-between;
				line-height: 64px;
				background: #21293c;
				cursor: pointer;
				flex-shrink: 0;
				align-items: center;

				&:hover {
					background: @mask03;
				}
				// 激活
				&.active {
					border: 1px solid @primary01;
					background: @secondary04;
				}

				.AI-left {
					display: flex;
					justify-content: space-between;
					color: @text01;
				}

				.ant-switch-small {
					min-width: 26px;
					height: 14px;
					line-height: 14px;
					background-color: @text03;
				}

				.ant-switch-handle {
					position: absolute;
					top: 1px;
					left: 1px;
					width: 12px;
					height: 12px;
					transition: all 0.2s ease-in-out;
				}

				.ant-switch-small.ant-switch-checked .ant-switch-handle {
					left: calc(100% - 12px) !important;
				}

				.ant-switch-checked {
					background-color: @secondary01;
				}
			}
		}
	}

	.ai-service-page-main {
		display: flex;
		height: calc(100vh - 220px);
		// height: 100%;
		// background-color: #fff;
		box-shadow: 0 0 10px @mask02;
		flex: 1;
		flex-direction: column;

		header {
			display: flex;
			height: 56px;
			border-bottom: 1px solid @borderColor01;
			padding: 0 24px;
			align-items: center;
			justify-content: space-between;

			h6 {
				margin: 0;
				font-size: 16px;
				font-weight: 700;
				color: @text01;
			}

			> div {
				display: flex;
				align-items: center;
				gap: 0 8px;
				font-size: 14px;
				color: @text02;
			}
		}

		.general-bar {
			display: flex;
			height: 56px;
			border-bottom: 1px solid @borderColor02;
			padding: 0 24px;
			background: rgba(22, 31, 49, 0.45);
			align-items: center;
			justify-content: space-between;

			.text {
				margin: 0;
				font-size: 14px;
				color: @text01;

				// &::before {
				// 	display: inline-block;
				// 	width: 3px;
				// 	height: 16px;
				// 	margin-right: 6px;
				// 	border-radius: 0 2px 2px 0;
				// 	background: @secondary04; //蓝色渐变
				// 	transform: translateY(3px);
				// 	content: '';
				// }
			}

			> div {
				display: flex;
				align-items: center;
				gap: 0 8px;
			}

			.reset-button {
				color: @text03;
			}
		}

		.form-wrap {
			overflow: auto;
			padding: 40px 64px;
			flex: 1;
		}
	}
}
</style>
